//配置路由的地方
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/routes";
import store from "@/store";
import Cookie from 'js-cookie';
//使用插件
Vue.use(VueRouter);

//1、先把VueRouter原型对象的push，replace保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//2、重写push|replace
//第一个参数：告诉原来的push，跳转的目标位置和传递了哪些参数
//第二个参数：成功回调
//第三个参数：失败回调
//call与apply的区别，call传参用逗号隔开，apply传递数组
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
        this,
        location,
        () => {
        },
        () => {
        }
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
        this,
        location,
        () => {
        },
        () => {
        }
    );
  }
};

//配置路由
let router = new VueRouter({
  routes,
  //控制滚动条
  scrollBehavior(to, from, savedPosition) {
    return {y: 0};
  },
});

//全局守卫，前置守卫
router.beforeEach(async (to, from, next) => {
  //let token = store.state.user.token;
  let token = Cookie.get("LY_TOKEN")
  let name = store.state.user.userInfo.username;
  if (token) {
    if (to.path === "/login" || to.path === "/register") {
      //登录了，不能再去登录或注册
      next("/home");
    } else {
      //登录了，去的不是login，可以去
      if (name) {
        //获取到了用户信息
        next();
      } else {
        //登录了，没有用户信息（刷新页面了）
        try {
          //派发action，获取用户信息
          await store.dispatch("getUserInfo");
          next();
        } catch (e) {
          //token过期了
          await store.dispatch("userLogout");
          next("/login");
        }
      }
    }
  } else {
    //未登录
    let toPath = to.path
    if (toPath.indexOf("/trade") !== -1 || toPath.indexOf("/pay") !== -1 || toPath.indexOf("/center") !== -1) {
      next("/login?redirect=" + toPath)
    } else {
      next();
    }
  }
});

export default router;
